<!-- AddRuleDialog.vue -->
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from "element-plus"
import { reactive, ref, watch } from "vue"
import { addRuleListAPI } from "./apis/index.ts"
/* ========== 类型 ========== */
interface FormModel {
  ruleNumber: string
  ruleName: string
  chargeType: "duration" | "turn" | "partition"
  freeDuration: number | null
  chargeCeiling: number | null
  durationTime: number | null
  durationPrice: number | null
  turnPrice: number | null
  partitionFrameTime: number | null
  partitionFramePrice: number | null
  partitionIncreaseTime: number | null
  partitionIncreasePrice: number | null
}

/* ========== props & emit ========== */
const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{
  (e: "update:modelValue", v: boolean): void
  (e: "success"): void
}>()

const visible = ref(props.modelValue)
watch(() => props.modelValue, val => (visible.value = val))
watch(visible, val => emit("update:modelValue", val))

/* ========== 表单 ========== */
const formRef = ref<FormInstance>()
const form = reactive<FormModel>({
  ruleNumber: "",
  ruleName: "",
  chargeType: "duration",
  freeDuration: null,
  chargeCeiling: null,
  durationTime: null,
  durationPrice: null,
  turnPrice: null,
  partitionFrameTime: null,
  partitionFramePrice: null,
  partitionIncreaseTime: null,
  partitionIncreasePrice: null
})

const rules = reactive<FormRules<FormModel>>({
  ruleNumber: [{ required: true, message: "请输入规则编号", trigger: "blur" }],
  ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  chargeType: [{ required: true, message: "请选择收费类型", trigger: "change" }]
})

/* ========== 提交 ========== */
const submitLoading = ref(false)
async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true

    try {
      const res = await addRuleListAPI(form)
      if (res.code === 10000) {
        ElMessage.success("新增成功")
        emit("success") // 通知父组件刷新数据
        emit("update:modelValue", false)
        handleClose()
      } else {
        ElMessage.error(res.message || "新增失败")
      }
    } catch {
      ElMessage.error("新增失败")
    }
    submitLoading.value = false
  })
}

function handleClose() {
  formRef.value?.resetFields()
  visible.value = false
}
</script>

<template>
  <el-dialog
    v-model="visible"
    width="680px"
    title="新增规则"
    :before-close="handleClose"
  >
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="计费规则编号" prop="ruleNumber">
          <el-input v-model="form.ruleNumber" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="计费规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="计费方式" prop="chargeType">
          <el-radio-group v-model="form.chargeType" size="small">
            <el-radio label="duration" border>
              时长收费
            </el-radio>
            <el-radio label="turn" border>
              按次收费
            </el-radio>
            <el-radio label="partition" border>
              分段收费
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="免费时长（分钟）">
              <el-input-number
                v-model="form.freeDuration"
                :min="0"
                :step="1"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收费上限（元）">
              <el-input-number
                v-model="form.chargeCeiling"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 动态计费区域 -->
        <el-form-item label="计费规则">
          <!-- 时长收费 -->
          <div v-if="form.chargeType === 'duration'" class="duration">
            每 <el-input-number v-model="form.durationTime" :min="0.5" :step="0.5" :precision="1" class="input-box" />
            小时，<el-input-number v-model="form.durationPrice" :min="0" :precision="2" class="input-box" /> 元
          </div>

          <!-- 按次收费 -->
          <div v-if="form.chargeType === 'turn'" class="turn">
            每次 <el-input-number v-model="form.turnPrice" :min="0" :precision="2" class="input-box" /> 元
          </div>

          <!-- 分段收费 -->
          <div v-if="form.chargeType === 'partition'" class="partition">
            <div class="item">
              <el-input-number v-model="form.partitionFrameTime" :min="1" :precision="0" class="input-box" />
              小时内，每小时收费
              <el-input-number v-model="form.partitionFramePrice" :min="0" :precision="2" class="input-box" /> 元
            </div>
            <div class="item">
              每增加
              <el-input-number v-model="form.partitionIncreaseTime" :min="1" :precision="0" class="input-box" />
              小时，增加
              <el-input-number v-model="form.partitionIncreasePrice" :min="0" :precision="2" class="input-box" /> 元
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button size="mini" @click="handleClose">
        取 消
      </el-button>
      <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmit">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.form-container {
  padding: 0 80px;
}
.input-box {
  width: 120px;
  margin: 0 8px;
}
.item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
</style>
